#!/usr/bin/env python
# -------
# Imports:
# -------
import os, logging, array, StringIO
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import users
from settings import *
from core.models import *
from datetime import datetime

# -----------------------------------------
class ThresholdImage(webapp.RequestHandler):
# -----------------------------------------
    # --------------------------------------
    def threshold(self, image, thresholdVal):
    # --------------------------------------
        # Load the image into pypng
        width, height, pixels, metadata = image.load()

        # Loop through the pixels in the image and threshold them
        thresholded = []
        for row in pixels:
            thresholdedRow = []
            for i in range(0, len(row), 3): 
                # Alias the pixel
                px = row[i:i+3]

                # Convert to grayscale & threshold
                gray = (px[0] + px[1] + px[2]) / 3.0
                val = 255 if gray > thresholdVal else 0
            
                # Store the new value
                thresholdedRow.append(val)

            # Store the new row
            thresholded.append(thresholdedRow)
        
        # Write the new image out to a string	
        writer = png.Writer(width, height, greyscale=True)
        thresholdedPNG = StringIO.StringIO()
        writer.write(thresholdedPNG, thresholded)
        thresholdedPNG = thresholdedPNG.getvalue()

        return (width, height, thresholdedPNG)

    # ------------
    def post(self):
    # ------------
        # Paramaters
        threshold = int(self.request.get('threshold'))
        thresholdVal = int(threshold)
        imgId = int(self.request.get('imgId'))

        # Query for the image
        image = Image.get_by_id(imgId)	
        
        # See if we've already done the thresholding... 
        tImgs = ThresholdedImage.all()
        tImgs.filter('source_image =', image)
        tImgs.filter('threshold =', thresholdVal)
        tImgs = tImgs.fetch(1)
        alreadyThresholded = (len(tImgs) != 0)

        if not alreadyThresholded:
           
            # Threshold the image
            (width, height,thresholdedPNG) = self.threshold(image, thresholdVal)

            # Store the thresholded image in the database 
            tImg = ThresholdedImage()
            tImg.image = thresholdedPNG
            tImg.image_width = width
            tImg.image_height = height
            tImg.format = 'png'
            tImg.source_image = image
            tImg.threshold = thresholdVal
            tImg.put()
        else:
            tImg = tImgs[0]

        # Return the ID of the new image
        self.response.out.write(tImg.key().id())
